const config = require('../nuxt.config.js')
const Koa = require('koa')
const cors = require('koa2-cors')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const redis = require('../framework/redis')

const routerHandler = require('../framework/server-router-handler')

const app = new Koa()

// Import and Set Nuxt.js options
config.dev = app.env !== 'production'

async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)
  host = process.env.LISTEN_HOST || '0.0.0.0'
  port = process.env.LISTEN_PORT || 3000

  await nuxt.ready()
  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  app.use(
    cors({
      credentials: true
    })
  )

  app.use(async (ctx, next) => {
    //这个redis客户端需要在视图渲染中获取data使用，所以要绑定在req对象上。因为只有req和res对象能传递到视图层。
    ctx.$nuxt = nuxt
    ctx.$redis = redis
    await next()
  })

  //主要的处理逻辑
  app.use(routerHandler)
  // app.use(router.routes()).use(router.allowedMethods())

  app.use(async (ctx) => {
    ctx.status = 200
    ctx.respond = false // 绕过koa内置对response的处理
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    await nuxt.render(ctx.req, ctx.res)
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
